# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.views import generic
import random
from django.shortcuts import render, get_object_or_404, redirect
from mathutils import genquestions
from django.db.models import F
from .forms import *
from .models import Question
# Create your views here.
from .models import *
from django.db.models import Q
from django.utils import timezone
from django.http import HttpResponseRedirect, Http404, HttpResponse
from comments.forms import CommentForm
import re
from django.db import IntegrityError

def test_view(request):
    if request.method == 'POST':
        for key, values in request.POST.lists():
            if not re.match(r'^csrf',key):
                print(key, values)

    return render(request, "test.html")
class TestView(generic.CreateView):
    form_class = MistakeForm
    template_name = 'test.html'

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.create_date = timezone.now()
        self.object.wrongcount = 1
        self.object.mistakeset = True
        solution = self.object.solution
        self.object.type = "custom"
        self.object.save()
        self.object.users.add(self.request.user)
        answers = [Answer(question=self.object, value=str(int(solution) + 1)),
                   Answer(question=self.object, value=str(int(solution) + 2)),
                   Answer(question=self.object, value=str(int(solution) - 1)),
                   Answer(question=self.object, value=solution, flag=True)]
        Answer.objects.bulk_create(answers)
        return super(TestView, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(TestView, self).get_context_data(**kwargs)
        context['wrongset'] = 'open'
        context['wrongsetadd'] = 'active'
        context['title'] = '错题列表'
        context['buttonname'] = '新增'
        return context


class Homepage(generic.ListView):
    model = Test
    template_name = 'mathtest/wrongsetpracticelist.html'

    def get_queryset(self):
        return Test.objects.filter(wrongset=True, user=self.request.user)

    def get_context_data(self, **kwargs):
        context = super(Homepage, self).get_context_data(**kwargs)
        context['home'] = 'open'
        context['stats'] = 'active'
        context['title'] = '测试统计'
        return context


class ExamList(generic.ListView):
    template_name = 'mathtest/examlist.html'

    def get_queryset(reqeust):
        return Test.objects.all()

    def get_context_data(self, **kwargs):
        context = super(ExamList, self).get_context_data(**kwargs)
        context['home'] = 'open'
        context['stats'] = 'active'
        return context


class OUtestresult(generic.ListView):
    model = Test
    template_name = 'mathtest/testlist.html'

    def get_queryset(self):
        return Test.objects.filter(wrongset=False, parent=None, user=self.request.user)

    def get_context_data(self, **kwargs):
        context = super(OUtestresult, self).get_context_data(**kwargs)
        context['oneunknow'] = 'open'
        context['OUtestresult'] = 'active'
        context['title'] = '测试结果'
        return context


class OUtestDetailView(generic.DetailView):
    model = Test
    template_name = 'mathtest/testdetail.html'

    def get_context_data(self, **kwargs):
        context = super(OUtestDetailView, self).get_context_data(**kwargs)
        context['oneunknow'] = 'open'
        context['OUtestresult'] = 'active'
        context['title'] = '测试概要'
        test_id = self.kwargs['pk']
        test = Test.objects.get(id=test_id)
        if str(test.score) == '100.0':
            context['message'] = '恭喜你没有错题!!!'
        chooses = []
        for i in test.choose_set.all():
            chooses.append(i.choose.id)
        context['chooses'] = chooses
        return context


class OUtestgenView(generic.ListView):
    model = Test
    template_name = 'mathtest/oneunknowlist.html'

    def get_queryset(self):
        level = self.kwargs['pk']
        length = 5
        if int(level) == 1:
            length = 100
        elif int(level) == 2:
            length = 20
        elif int(level) == 3:
            level = 1
            length = 1
        eq = Question.objects.filter(level=level, type='system').order_by('?')[:length]
        newtest = Test.objects.create(user=self.request.user)
        newtest.questions.add(*list(eq))
        return Test.objects.filter(id=newtest.id)

    def get_context_data(self, **kwargs):
        context = super(OUtestgenView, self).get_context_data(**kwargs)
        context['oneunknow'] = 'open'
        context['OUtestgen'] = 'active'
        context['title'] = '习题集'

        return context


# 新测试,调用此处评分
def OUNewtestscore(request, test_id):
    score = 0
    if request.method == 'POST':
        test = Test.objects.get(id=test_id)
        questions = test.questions.all()
        totalquestions = questions.count()
        rightquesitons = 0
        for q in questions:
            choose = Answer.objects.get(id=request.POST.get(str(q.id), ''))
            Choose.objects.get_or_create(test=test, question=q, choose=choose)
            if choose.flag:
                rightquesitons += 1
            else:
                q.users.add(request.user)
                Question.objects.filter(id=q.id).update(wrongcount=F('wrongcount') + 1, mistakeset=True,archive=False)
                # user_q=Question.objects.filter(user=request.user,expresstion=q.expresstion)
                # if user_q:
                #     user_q.update(wrongcount=F('wrongcount') + 1)
                # else:
                #     q.pk=None
                #     q.user=request.user
                #     q.wrongcount=1
                #     q.mistakeset=True
                #     q.type='custom'
                #     q.save()
                # #Question.objects.filter(id=q.id).update(wrongcount=F('wrongcount') + 1, mistakeset=True)
        score = int(float(rightquesitons) / float(totalquestions) * 100)
        begin_time = test.testdate
        end_time = timezone.now()
        complete_time = str(end_time - begin_time).split(".")[0]
        Test.objects.filter(id=test_id).update(score=score, complete_time=complete_time)
    test = Test.objects.get(id=test_id)
    chooses = []
    for i in test.choose_set.all():
        chooses.append(i.choose.id)
    context = {
        "title": '上次练习结果',
        "oneunknow": 'open',
        "lasttest": 'active',
        "test": test,
        "chooses": chooses
    }
    return render(request, "mathtest/newtestdetail.html", context)


def redoTestWrong(request, test_id):
    try:
        test = Test.objects.get(id=test_id)
    except:
        raise Http404
    score = 0
    test = Test.objects.get(id=test_id)
    questions = test.questions.all()
    new_questions = []
    for q in questions:
        try:
            c = Choose.objects.get(test=test, question=q)
        except:
            raise Http404
        if not c.choose.flag:
            new_questions.append(q)
    newtest = Test.objects.create(parent=test, user=request.user)
    newtest.questions.add(*new_questions)

    context = {
        "title": '重做错题',
        "oneunknow": 'open',
        "OUtestresult": 'active',
        "test": newtest,
    }
    return render(request, "mathtest/redotest.html", context)


def redoTestWrongScore(request, test_id):
    if request.method == 'POST':
        test = Test.objects.get(id=test_id)
        questions = test.questions.all()
        totalquestions = questions.count()
        rightquesitons = 0
        for q in questions:
            choose = Answer.objects.get(id=request.POST.get(str(q.id), ''))
            Choose.objects.get_or_create(test=test, question=q, choose=choose)
            if choose.flag:
                rightquesitons += 1
            else:
                Question.objects.filter(id=q.id).update(wrongcount=F('wrongcount') + 1, mistakeset=True,archive=False)
        score = int(float(rightquesitons) / float(totalquestions) * 100)
        begin_time = test.testdate
        end_time = timezone.now()
        complete_time = str(end_time - begin_time).split(".")[0]
        Test.objects.filter(id=test.id).update(score=score, complete_time=complete_time)
    test = Test.objects.get(id=test.id)
    chooses = []
    for i in test.choose_set.all():
        chooses.append(i.choose.id)
    context = {
        "title": '重做结果',
        "oneunknow": 'open',
        "lasttest": 'active',
        "test": test,
        "chooses": chooses
    }
    return render(request, "mathtest/newtestdetail.html", context)


class MistakeListView(generic.ListView):
    model = Question
    template_name = 'mathtest/mistakelist.html'

    def get_queryset(self):
        if self.request.user.id==1:
            return Question.objects.filter(mistakeset=True, archive=False).order_by("-create_date","-wrongcount")
        else:
            return self.request.user.question_set.filter(mistakeset=True, archive=False).order_by("-create_date",
                                                                                              "-wrongcount")

    def get_context_data(self, **kwargs):
        context = super(MistakeListView, self).get_context_data(**kwargs)
        context['wrongset'] = 'open'
        context['wrongsetlist'] = 'active'
        context['title'] = '错题列表'
        return context


class MistakeCreateView(generic.CreateView):
    form_class = MistakeForm
    template_name = 'mathtest/mistake_form.html'

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.create_date = timezone.now()
        self.object.mistakeset = True
        solution = self.object.solution
        self.object.type = "custom"
        self.object.save()
        self.object.users.add(self.request.user)
        answers = [Answer(question=self.object, value=str(int(solution) + 1)),
                   Answer(question=self.object, value=str(int(solution) + 2)),
                   Answer(question=self.object, value=str(int(solution) - 1)),
                   Answer(question=self.object, value=solution, flag=True)]
        Answer.objects.bulk_create(answers)
        return super(MistakeCreateView, self).form_valid(form)

    def get_context_data(self, **kwargs):
        context = super(MistakeCreateView, self).get_context_data(**kwargs)
        context['wrongset'] = 'open'
        context['wrongsetadd'] = 'active'
        context['title'] = '错题列表'
        context['buttonname'] = '新增'
        #context['messages'] = 'adasdasda'
        return context


class MistakeDetailView(generic.DetailView):
    model = Question
    template_name = 'mathtest/mistakedetail.html'

    def get_context_data(self, **kwargs):
        context = super(MistakeDetailView, self).get_context_data(**kwargs)
        context['wrongset'] = 'open'
        if super(MistakeDetailView, self).get_object().archive:
            context['mistakearchivelist'] = 'active'
        else:
            context['wrongsetlist'] = 'active'
        context['title'] = '错题详情'
        return context


def mistake_detail_view(request, pk):
    instance = get_object_or_404(Question, id=pk)

    initial_data = {
        "content_type": instance.get_content_type,
        "object_id": instance.id
    }
    form = CommentForm(request.POST or None, initial=initial_data)
    if form.is_valid():
        c_type = form.cleaned_data.get("content_type")
        content_type = ContentType.objects.get(model=c_type)
        obj_id = form.cleaned_data.get('object_id')
        content_data = form.cleaned_data.get("content")
        parent_obj = None
        try:
            parent_id = int(request.POST.get("parent_id"))
        except:
            parent_id = None

        if parent_id:
            parent_qs = Comment.objects.filter(id=parent_id)
            if parent_qs.exists() and parent_qs.count() == 1:
                parent_obj = parent_qs.first()

        new_comment, created = Comment.objects.get_or_create(
            user=request.user,
            content_type=content_type,
            object_id=obj_id,
            content=content_data,
            parent=parent_obj,
        )
        return HttpResponseRedirect(new_comment.content_object.get_absolute_url())

    comments = instance.comments

    if instance.archive:
        active = 'mistakearchivelist'
    else:
        active = 'wrongsetlist'
    context = {
        "wrongset": "open",
        "instance": instance,
        "title" : '错题详情',
        "%s"%active: "active",
        "comments": comments,
        "comment_form": form,
    }

    return render(request, "mathtest/mistakedetail.html", context)


class MistakeUpdateView(generic.UpdateView):
    form_class = MistakeForm
    template_name = 'mathtest/mistake_form.html'

    def get_object(self, *args, **kwargs):
        Quesiton = get_object_or_404(Question, pk=self.kwargs['pk'])
        return Quesiton

    def get_context_data(self, **kwargs):
        context = super(MistakeUpdateView, self).get_context_data(**kwargs)
        context['wrongset'] = 'open'
        context['wrongsetlist'] = 'active'
        context['title'] = '错题列表'
        context['buttonname'] = '更新'
        return context


class MistakeArchiveListView(generic.ListView):
    model = Question
    template_name = 'mathtest/mistakelist.html'

    def get_queryset(self):
        return self.request.user.question_set.filter(mistakeset=False,
                                                     archive=True).order_by("-create_date", "-wrongcount")

    def get_absolute_url(self):
        return reverse("mathtest:mistakearchivelist")

    def get_context_data(self, **kwargs):
        context = super(MistakeArchiveListView, self).get_context_data(**kwargs)
        context['wrongset'] = 'open'
        context['mistakearchivelist'] = 'active'
        context['title'] = '归档错题列表'
        return context


def archiveQuestion(request, pk):
    Question.objects.filter(id=pk).update(archive=True, mistakeset=False)
    return redirect("mathtest:mistakelist")


def resetToMistakeSetQuestion(request, pk):
    Question.objects.filter(id=pk).update(archive=False, mistakeset=True)
    return redirect("mathtest:mistakearchivelist")


class MistakePracticeListView(generic.ListView):
    model = Test
    template_name = 'mathtest/mistakepractise.html'

    def get_queryset(self, **kwargs):
        # #questions = Question.objects.filter(topic__id=self.kwargs['pk'], archive=False,user__in=self.request.users).order_by("-create_date",
        #
        #                                                                                       "-wrongcount")
        questions = self.request.user.question_set.filter(topic__id=self.kwargs['pk'], mistakeset=True,
                                                          archive=False).order_by("-create_date", "-wrongcount")

        newtest = Test.objects.create(wrongset=True, topic_id=self.kwargs['pk'], user=self.request.user)
        newtest.questions.add(*list(questions))
        return Test.objects.filter(id=newtest.id)

    def get_context_data(self, **kwargs):
        context = super(MistakePracticeListView, self).get_context_data(**kwargs)
        context['wrongset'] = 'open'
        context['mistakepratice'] = 'active'
        context['title'] = '错题练习'
        return context


def MistakeNewtestscore(request, test_id):
    score = 0
    if request.method == 'POST':
        test = Test.objects.get(id=test_id)
        questions = test.questions.all()
        totalquestions = questions.count()
        rightquesitons = 0
        for q in questions:
            choose = Answer.objects.get(id=request.POST.get(str(q.id), ''))
            Choose.objects.get_or_create(test=test, question=q, choose=choose)
            if choose.flag:
                rightquesitons += 1
            else:
                Question.objects.filter(id=q.id).update(wrongcount=F('wrongcount') + 1, mistakeset=True)

        score = int(float(rightquesitons) / float(totalquestions) * 100)
        begin_time = test.testdate
        end_time = timezone.now()
        complete_time = str(end_time - begin_time).split(".")[0]
        Test.objects.filter(id=test_id).update(score=score, complete_time=complete_time)
    test = Test.objects.get(id=test_id)
    chooses = []
    for i in test.choose_set.all():
        chooses.append(i.choose.id)
    context = {
        "title": '上次练习结果',
        "wrongset": 'open',
        "mistakepratice": 'active',
        "test": test,
        "chooses": chooses
    }
    return render(request, "mathtest/newmistakedetail.html", context)


def redoMistakeWrong(request, test_id):
    try:
        test = Test.objects.get(id=test_id)
    except:
        raise Http404
    score = 0
    test = Test.objects.get(id=test_id)
    questions = test.questions.all()
    new_questions = []
    for q in questions:
        try:
            c = Choose.objects.get(test=test, question=q)
        except:
            raise Http404
        if not c.choose.flag:
            new_questions.append(q)
    newtest = Test.objects.create(parent=test, wrongset=True, user=request.user)
    newtest.questions.add(*new_questions)

    context = {
        "title": '重做错题',
        "wrongset": 'open',
        "mistakepratice": 'active',
        "test": newtest,
    }
    return render(request, "mathtest/redomistakewrong.html", context)


def redoMistakeWrongScore(request, test_id):
    if request.method == 'POST':
        test = Test.objects.get(id=test_id)
        questions = test.questions.all()
        totalquestions = questions.count()
        rightquesitons = 0
        for q in questions:
            choose = Answer.objects.get(id=request.POST.get(str(q.id), ''))
            Choose.objects.get_or_create(test=test, question=q, choose=choose)
            if choose.flag:
                rightquesitons += 1
            else:
                Question.objects.filter(id=q.id).update(wrongcount=F('wrongcount') + 1, mistakeset=True)
        score = int(float(rightquesitons) / float(totalquestions) * 100)
        begin_time = test.testdate
        end_time = timezone.now()
        complete_time = str(end_time - begin_time).split(".")[0]
        Test.objects.filter(id=test.id).update(score=score, complete_time=complete_time)
    test = Test.objects.get(id=test.id)
    chooses = []
    for i in test.choose_set.all():
        chooses.append(i.choose.id)
    context = {
        "title": '重做结果',
        "wrongset": 'open',
        "mistakepratice": 'active',
        "test": test,
        "chooses": chooses
    }
    return render(request, "mathtest/newmistakedetail.html", context)


class MistakePracticeResult(generic.ListView):
    model = Test
    template_name = 'mathtest/wrongsetpracticelist.html'

    def get_queryset(self):
        return Test.objects.filter(wrongset=True, user=self.request.user, parent=None)

    def get_context_data(self, **kwargs):
        context = super(MistakePracticeResult, self).get_context_data(**kwargs)
        context['wrongset'] = 'open'
        context['mistakepracticeresult'] = 'active'
        context['title'] = '测试列表'
        return context


class MistakepracticeDetailView(generic.DetailView):
    model = Test
    template_name = 'mathtest/mistakepracticedetail.html'

    def get_context_data(self, **kwargs):
        context = super(MistakepracticeDetailView, self).get_context_data(**kwargs)
        context['wrongset'] = 'open'
        context['mistakepracticeresult'] = 'active'
        context['title'] = '练习概要'
        test_id = self.kwargs['pk']
        print test_id
        test = Test.objects.get(id=test_id)
        if str(test.score) == '100.0':
            context['message'] = '恭喜你没有错题!!!'
        chooses = []
        for i in test.choose_set.all():
            chooses.append(i.choose.id)
        context['chooses'] = chooses
        return context

def exam_add(request,test_id=''):
    exist = ''
    if request.method == 'POST':
        questions={}

        for key, value in request.POST.lists():
            if re.match(r'^question',key) :
                questions[key]=request.POST.getlist(key, '')
            if re.match(r'examname',key):
                examname=value[0]
        q_objs=[]
        print test_id
        if  test_id:
            newtest=Test.objects.get(id=test_id)
            exist=True
        else:
            newtest = Test.objects.create(wrongset=True, user=request.user, type='exam',name=examname)
        for k,v in questions.items():
            expresstion,solution,type=v
            if  expresstion:
                if type == 'choose':
                    question,flag=Question.objects.get_or_create(expresstion=expresstion,defaults={'solution':solution,'type':'exam'})
                    if flag:
                        answers = [Answer(question=question, value=str(int(solution) + 1)),
                               Answer(question=question, value=str(int(solution) + 2)),
                               Answer(question=question, value=str(int(solution) - 1)),
                               Answer(question=question, value=solution, flag=True)]
                        Answer.objects.bulk_create(answers)
                    q_objs.append(question)
                elif type == 'fill':
                    question, flag = Question.objects.get_or_create(expresstion=expresstion,
                                                                    defaults={'solution': solution, 'type': 'exam','qtype':'fill'})
                    #question, flag = Question.objects.get_or_create(expresstion=expresstion, solution=solution,type='exam',qtype='fille')
                    Choose.objects.get_or_create(question=question,test=newtest)
                    q_objs.append(question)
                elif type == 'resolve':
                    question, flag = Question.objects.get_or_create(expresstion=expresstion,
                                                                    defaults={'solution': solution, 'type': 'exam',
                                                                              'qtype': 'resolve'})
                    #question, flag = Question.objects.get_or_create(expresstion=expresstion, solution=solution,type='exam',qtype='resolve')
                    Choose.objects.get_or_create(question=question,test=newtest)
                    q_objs.append(question)
        newtest.questions.add(*list(q_objs))

    context = {
        "exam": "open",
        "title" : '错题详情',
        "examadd": "active",
        "exist":exist,

    }
    return render(request, "mathtest/examadd.html",context)
class ExamListView(generic.ListView):
    model = Test
    template_name = 'mathtest/examlist.html'

    def get_queryset(self):
        return Test.objects.filter(type='exam').order_by("-testdate")

    def get_context_data(self, **kwargs):
        context = super(ExamListView, self).get_context_data(**kwargs)
        context['exam'] = 'open'
        context['examlist'] = 'active'
        context['title'] = '试卷列表'
        return context
class ExamDetailView(generic.DetailView):
    model = Test
    template_name = 'mathtest/examdetail.html'

    def get_context_data(self, **kwargs):
        context = super(ExamDetailView, self).get_context_data(**kwargs)
        context['exam'] = 'open'
        context['examlist'] = 'active'
        context['title'] = '试卷详情'
        return context